/*
 * eth_connect.c
 *
 *  Created on: Jul 26, 2020
 *      Author: liwei
 */
#include "eth_connect.h"
#include "blink.h"
#include "config_app.h"
#include "eth_svc.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "myqueue.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "sntp_svc.h"
#include "tcpSocket_tsk.h"
#include "tcp_socketServer_tsk.h"
// #include "J_http.h"
extern int chint_web_stop();
extern int chint_web_init();

uint8_t mEthConnected = 0;

static const char* TAG = "Eth_Connect";

/* Set dhcp acquired IP information to mPartitionTable.tEthernetConfig and save to nvs flash */
static void vEth_Dhcp_GetIP_Save_Flash(esp_netif_ip_info_t* ip_info)
{
    uint32_t uiIndex;
    uint32_t uiSize;
    if (mPartitionTable.tEthernetConfig.EthernetIPType == ETHERNET_IP_TYPE_DHCP) {
        mPartitionTable.tEthernetConfig.usIPH = ip4_addr1_16(&(ip_info->ip)) << 8U | (ip4_addr2_16(&(ip_info->ip)) & 0xFF);
        mPartitionTable.tEthernetConfig.usIPL = ip4_addr3_16(&(ip_info->ip)) << 8U | (ip4_addr4_16(&(ip_info->ip)) & 0xFF);
        mPartitionTable.tEthernetConfig.usGateWayH = ip4_addr1_16(&(ip_info->gw)) << 8U | (ip4_addr2_16(&(ip_info->gw)) & 0xFF);
        mPartitionTable.tEthernetConfig.usGateWayL = ip4_addr3_16(&(ip_info->gw)) << 8U | (ip4_addr4_16(&(ip_info->gw)) & 0xFF);
        mPartitionTable.tEthernetConfig.usSubMaskH = ip4_addr1_16(&(ip_info->netmask)) << 8U | (ip4_addr2_16(&(ip_info->netmask)) & 0xFF);
        mPartitionTable.tEthernetConfig.usSubMaskL = ip4_addr3_16(&(ip_info->netmask)) << 8U | (ip4_addr4_16(&(ip_info->netmask)) & 0xFF);

        /* write acquired IP, GateWay, net mask address infor to nvs flash */
        uiIndex = PARTITION_TABLE_ADDR_EHERNET_IP_HADDR - 1; // ETH IP start address: 0x0021 - 1
        uiSize = 6; // IPH, IPL, GateWayH, GateWayL, SubMaskH, SubMaskl,  write to 6 registers.
        while (uiSize) {
            CFG_vSaveConfig(uiIndex++);
            uiSize--;
        }
    }
}

/* copy eth connected status from ETH_vRegister_Callback() */
static void vEth_Event_CallBack(ETHEventTPDF* tEvent)
{
    static uint8_t ucSntpDone = 0;
    switch (tEvent->tType) {
    case ETH_IP_GOT:
        mEthConnected = 1;
        vEth_Dhcp_GetIP_Save_Flash(&(((ip_event_got_ip_t*)tEvent->tTag)->ip_info));
        if (!ucSntpDone) {
            SNTP_vInit(vSntpSendTime_CallBack);
            ucSntpDone = 1;
        }
        chint_web_init();
        break;
    case ETH_PHY_DISCONNECTED:
        chint_web_stop();
        mEthConnected = 0;
        vTcp_SocketServer_Close();
        gpio_set_level(IOT_LED, LED_OFF);
        break;
    default:
        break;
    }
}

/*Use function return Ethernet Network link status*/
uint8_t Eth_Connected_Status(void)
{
    return mEthConnected;
}

/*Inialize ehternet hardware base and register ethernet callback*/
void vETH_Init(void)
{
    ETH_Base_Init(&mPartitionTable.tEthernetConfig);
    ETH_vRegister_Callback(vEth_Event_CallBack);
}
